﻿using SIAKAD.Helper;
using SIAKADCORE.Controllers;
using SIAKADCORE.Helpers;
using SIAKADCORE.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SIAKAD
{
    public partial class ViewPengguna : System.Web.UI.Page
    {
        private DataSet dsPengguna;

        private Dictionary<string,string> roles;
        private List<string> types;

        protected void Page_Load(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine(Page.IsCallback);
            System.Diagnostics.Debug.WriteLine(Page.IsPostBack);
            if (!Page.IsPostBack && !Page.IsCallback)
            {
                this.FillRoles();
                this.FillTypes();

                string search = Request.QueryString["search"];
                if (search != null)
                {
                    this.InitTabelPenggunaSearch(search);
                }
                else
                {
                    this.InitTabelPengguna();
                }
            }
        }

        private void FillTypes()
        {
            types = new List<string>();
            
            types.Add("Dosen");
            types.Add("Mahasiswa");
            types.Add("Pegawai TU");
            
            types.ForEach(item => this.ddlAddMahasiswaDosen.Items.Add(item));

            this.SetLabel();
            this.Cek();
        }

        private void SetLabel()
        {
            if (this.ddlAddMahasiswaDosen.SelectedItem.Text.Equals("Dosen"))
            {
                this.ltNama.Text = "Nama Dosen";
                this.ltNIPNRP.Text = "NIP";
            }
            else if (this.ddlAddMahasiswaDosen.SelectedItem.Text.Equals("Mahasiswa"))
            {
                this.ltNama.Text = "Nama Mahasiswa";
                this.ltNIPNRP.Text = "NRP";
            }
            else if (this.ddlAddMahasiswaDosen.SelectedItem.Text.Equals("Pegawai TU"))
            {
                this.ltNama.Text = "Nama Pegawai TU";
                this.ltNIPNRP.Text = "NIP";
            }

            this.txtAddNIPNRP.Text = string.Empty;
            this.txtAddNama.Text = string.Empty;
        }

        private void Cek()
        {
            if (this.ddlAddMahasiswaDosen.SelectedItem.Text.Equals("Dosen"))
            {
                this.ddlAddRole.Items.Clear();
                var temp = roles.Where(pair => pair.Key != "RL006" && pair.Key != "RL007");

                foreach (KeyValuePair<string, string> pair in temp)
                {
                    this.ddlAddRole.Items.Add(new ListItem(pair.Value, pair.Key));
                }
            }
            else if (this.ddlAddMahasiswaDosen.SelectedItem.Text.Equals("Mahasiswa"))
            {
                this.ddlAddRole.Items.Clear();
                var temp = roles.Where(pair => pair.Key == "RL006");

                foreach (KeyValuePair<string, string> pair in temp)
                {
                    this.ddlAddRole.Items.Add(new ListItem(pair.Value, pair.Key));
                }
            }
            else if (this.ddlAddMahasiswaDosen.SelectedItem.Text.Equals("Pegawai TU"))
            {
                this.ddlAddRole.Items.Clear();
                var temp = roles.Where(pair => pair.Key == "RL007");

                foreach (KeyValuePair<string, string> pair in temp)
                {
                    this.ddlAddRole.Items.Add(new ListItem(pair.Value, pair.Key));
                }
            }
        }

        private void FillRoles()
        {
            roles = new Dictionary<string,string>();
            var dataset = new DataSet();

            bool isSuccess = RoleController.GetTabel(out dataset);
            if (isSuccess)
            {
                foreach (DataRow row in dataset.Tables[0].Rows)
                {
                    roles.Add(row[0].ToString(), row[1].ToString());
                }

                foreach (KeyValuePair<string, string> pair in roles)
                {
                    this.ddlAddRole.Items.Add(new ListItem(pair.Value, pair.Key));
                }
            }
        }

        private void InitTabelPengguna()
        {
            bool isSuccess = UserController.GetTabelPreview(out this.dsPengguna);
            if (isSuccess)
            {
                this.gvPengguna.DataSource = this.dsPengguna.Tables[0];
                this.gvPengguna.DataBind();
            }
        }

        private void InitTabelPenggunaSearch(string username)
        {
            bool isSuccess = UserController.Cari(username, out this.dsPengguna);
            if (isSuccess)
            {
                this.gvPengguna.DataSource = this.dsPengguna.Tables[0];
                this.gvPengguna.DataBind();
            }
        }


        protected void gvPengguna_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("deleteRecord"))
            {
                int index = Convert.ToInt32(e.CommandArgument);
                this.DeleteCommand(index);
            }
            else if (e.CommandName.Equals("updateRecord"))
            {
                int index = Convert.ToInt32(e.CommandArgument);
                this.EditCommand(index);
            }
        }

        private void EditCommand(int index)
        {
            this.SetHiddenField(index, ref this.hfUpdateID);

            var temp = UserController.GetUser(this.hfUpdateID.Value);
            if (temp.IdUser == string.Empty) return;

            this.ddlEditRole.Items.Clear();
            this.FillRoles();

            if (temp.IdMahasiswa.Equals(string.Empty) && temp.IdPegawai.Equals(string.Empty))
            {
                var tempRoles = roles.Where(pair => pair.Key != "RL006" && pair.Key != "RL007");

                foreach (KeyValuePair<string, string> pair in tempRoles)
                {
                    this.ddlEditRole.Items.Add(new ListItem(pair.Value, pair.Key));
                }
            }
            else if (temp.IdDosen.Equals(string.Empty) && temp.IdPegawai.Equals(string.Empty))
            {
                var tempRoles = roles.Where(pair => pair.Key == "RL006");

                foreach (KeyValuePair<string, string> pair in tempRoles)
                {
                    this.ddlEditRole.Items.Add(new ListItem(pair.Value, pair.Key));
                }
            }
            else if (temp.IdDosen.Equals(string.Empty) && temp.IdMahasiswa.Equals(string.Empty))
            {
                var tempRoles = roles.Where(pair => pair.Key == "RL007");

                foreach (KeyValuePair<string, string> pair in tempRoles)
                {
                    this.ddlEditRole.Items.Add(new ListItem(pair.Value, pair.Key));
                }
            }

            this.ddlEditRole.Items.FindByValue(temp.IdRole).Selected = true;

            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ShowEditModalScript", PenggunaScript.ShowEdit(), false);
        }

        private void DeleteCommand(int index)
        {
            this.SetHiddenField(index, ref this.hfDeleteID);

            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ShowDeleteModalScript", PenggunaScript.ShowDelete(), false);
        }

        protected void SetHiddenField(int index, ref HiddenField hiddenField)
        {
            string code = gvPengguna.DataKeys[index].Value.ToString();
            hiddenField.Value = code;
        }

        protected void gvPengguna_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.gvPengguna.PageIndex = e.NewPageIndex;
            
            string search = Request.QueryString["search"];
            if (search != null)
            {
                this.InitTabelPenggunaSearch(search);
            }
            else
            {
                this.InitTabelPengguna();
            }

            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "PagingScript", SiakadScript.PagerStyle(), false);
        }

        protected void btAdd_Click(object sender, EventArgs e)
        {
            this.txtAddNama.Text = string.Empty;
            this.txtAddNIPNRP.Text = string.Empty;
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ShowAddModalScript", PenggunaScript.ShowAdd(), false);
        }

        protected void btAddPengguna_Click(object sender, EventArgs e)
        {
            if (txtAddNama.Text == "" && txtAddNIPNRP.Text == "")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "PagerStyle", SiakadScript.PagerStyle(), false);
                return;
            }

            if (this.ddlAddMahasiswaDosen.SelectedItem.Text.Equals("Dosen"))
            {
                var dsn = new SIAKADCORE.Models.Dosen
                {
                    IdDosen = DosenController.GetID(),
                    NamaDosen = txtAddNama.Text,
                    Nip = txtAddNIPNRP.Text
                };

                var usr = new User
                {
                    IdUser = UserController.GetID(),
                    Username = dsn.Nip,
                    Password = new AesCipherUtility("reintasa", "cantik").Encrypt(dsn.Nip),
                    IdRole = ddlAddRole.SelectedValue,
                    IdDosen = dsn.IdDosen
                };

                UserController.Tambah(usr, dsn);
            }
            else if (this.ddlAddMahasiswaDosen.SelectedItem.Text.Equals("Mahasiswa"))
            {
                var mhs = new SIAKADCORE.Models.Mahasiswa
                {
                    IdMahasiswa = MahasiswaController.GetID(),
                    NamaMahasiswa = txtAddNama.Text,
                    Nrp = txtAddNIPNRP.Text
                };

                var usr = new User
                {
                    IdUser = UserController.GetID(),
                    Username = mhs.Nrp,
                    Password = new AesCipherUtility("reintasa", "cantik").Encrypt(mhs.Nrp),
                    IdRole = ddlAddRole.SelectedValue,
                    IdMahasiswa = mhs.IdMahasiswa
                };

                UserController.Tambah(usr, mhs);
            }
            else if (this.ddlAddMahasiswaDosen.SelectedItem.Text.Equals("Pegawai TU"))
            {
                var pgw = new SIAKADCORE.Models.Pegawai
                {
                    IdPegawai = PegawaiController.GetID(),
                    NamaPegawai = txtAddNama.Text,
                    Nip = txtAddNIPNRP.Text
                };

                var usr = new User
                {
                    IdUser = UserController.GetID(),
                    Username = pgw.Nip,
                    Password = new AesCipherUtility("reintasa", "cantik").Encrypt(pgw.Nip),
                    IdRole = ddlAddRole.SelectedValue,
                    IdMahasiswa = pgw.IdPegawai
                };

                UserController.Tambah(usr, pgw);
            }

            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "HideAddModalScript", PenggunaScript.SuccessAdd(), false);

            ToCurrentPageIndex();
        }

        protected void ddlAddMahasiswaDosen_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.ddlAddMahasiswaDosen.Items.Count > 0)
            {
                this.FillRoles();
                this.Cek();
                this.SetLabel();

                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "PagerStyle", SiakadScript.PagerStyle(), false);
            }
        }

        protected void btDeletePengguna_Click(object sender, EventArgs e)
        {
            var temp = UserController.GetUser(this.hfDeleteID.Value);
            if (temp.IdUser == string.Empty) return;

            bool isUserDeleted = UserController.Hapus(temp.IdUser);
            if (isUserDeleted)
            {
                if (temp.IdMahasiswa.Equals(string.Empty) && temp.IdPegawai.Equals(string.Empty))
                {
                    DosenController.Hapus(temp.IdDosen);
                }
                else if(temp.IdDosen.Equals(string.Empty) && temp.IdPegawai.Equals(string.Empty))
                {
                    MahasiswaController.Hapus(temp.IdMahasiswa);
                }
                else if (temp.IdDosen.Equals(string.Empty) && temp.IdMahasiswa.Equals(string.Empty))
                {
                    PegawaiController.Hapus(temp.IdPegawai);
                }
            }

            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "HideDeleteModalScript", PenggunaScript.SuccessDelete(), false);

            ToCurrentPageIndex();
        }

        private void ToCurrentPageIndex()
        {
            int index = gvPengguna.PageIndex;
            string search = Request.QueryString["search"];
            
            if (search != null)
            {
                this.InitTabelPenggunaSearch(search);
            }
            else
            {
                this.InitTabelPengguna();
            }

            try
            {
                gvPengguna.PageIndex = index;
            }
            catch
            {
                gvPengguna.PageIndex = index--;
            }

            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "PagerStyle2", SiakadScript.PagerStyle(), false);
        }

        protected void btEditRole_Click(object sender, EventArgs e)
        {
            UserController.UbahRole(this.ddlEditRole.SelectedValue, this.hfUpdateID.Value);

            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "HideEditModalScript", PenggunaScript.SuccessEdit(), false);
            ToCurrentPageIndex();
        }

        protected void btSearch_Click(object sender, EventArgs e)
        {
            string tempUsername = this.txtSearch.Text;
            string url = Request.Url.GetLeftPart(UriPartial.Path);
            Response.Redirect(String.Format("{0}?search={1}", url, tempUsername));
        }
    }
}